/* eslint-disable no-useless-constructor */
import React, { createRef } from 'react'
import { Form, Input, Button, Checkbox, Row, Col, message } from 'antd'
import { getCaptchaImage } from '@/api/index'
import { withRouter } from 'react-router-dom'
import { validateUser } from '../../../utils/validate'
import Store from '../../../store/index'
import Cookies from 'js-cookie'
import '../index.scss'

interface IProps {
  parent?: any
  history?: any
}
interface IState {
  logining: boolean
  captchaImage: any
  uuid: string
  userName: string
  password: string
  rememberPassword: boolean
}
class Index extends React.Component<IProps, IState> {
  parent: any
  form: { current: any }
  state: any
  constructor(props: any) {
    super(props)
    this.form = createRef()
    this.parent = props.parent
    this.state = {
      logining: false,
      captchaImage: {}, // 验证码
      uuid: '',
      userName: '',
      password: '',
      rememberPassword: false,
    }
  }
  UNSAFE_componentWillMount() {
    let account = Cookies.get('rememberPassword')

    if (account) {
      console.log(account)
      account = JSON.parse(account)
      this.setState({
        userName: account.userName,
        password: account.password,
        rememberPassword: true,
      })
    }
  }
  async componentDidMount() {
    this.getCheckCode()
  }
  async getCheckCode() {
    const res: any = await getCaptchaImage()
    if (res.code === 200) {
      this.setState({ captchaImage: res.img, uuid: res.uuid })
    }
  }

  toRegister = () => {
    //注册
    console.log('哈哈哈哈', this)
    this.parent.changeView('register')
  }
  submit = async () => {
    const { getFieldValue } = this.form.current
    console.log(this.form.current)
    this.form.current
      .validateFields(['username', 'password', 'checkCode'])
      .then(async values => {
        const params = {
          userName: getFieldValue('username'),
          password: getFieldValue('password'),
          verificationCode: getFieldValue('checkCode'),
          uuid: this.state.uuid,
        }
        this.setState({ logining: true })
        Store.Login(params, res => {
          if (res.status == 'error') {
            message.error(res.msg)
            console.log('执行了吗')
            this.setState({ logining: false })
          }
          if (res.code == 200) {
            message.success('登录成功')
            setTimeout(() => {
              console.log(this)
              this.props.history.goBack()
            }, 1000)
          }
          console.log(res)
        })
          .then(res => {
            console.log(res)
          })
          .catch(err => {
            console.log('出错率')
          })
        // 判断是否需要记住密码
        if (this.state.rememberPassword) {
          Cookies.set(
            'rememberPassword',
            {
              userName: getFieldValue('username'),
              password: getFieldValue('password'),
            },
            { expires: 3 }
          ) // 记住
        } else {
          Cookies.remove('rememberPassword')
        }
      })
      .catch(err => {
        console.log(err)
      })
  }
  reset = () => {
    this.getCheckCode()
  }
  render(): JSX.Element {
    return (
      <div>
        <div className='login-box'>
          <Form
            ref={this.form}
            name='basic'
            labelAlign='left'
            initialValues={{
              username: this.state.userName,
              password: this.state.password,
            }}
          >
            <Form.Item
              label='用户名'
              labelCol={{ span: 4 }}
              name='username'
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
                {
                  validator: validateUser,
                },
              ]}
            >
              <Input placeholder='手机号或邮箱' />
            </Form.Item>

            <Form.Item
              label='密码'
              labelCol={{ span: 4 }}
              name='password'
              rules={[
                {
                  required: true,
                  message: '请输入密码!',
                },
              ]}
            >
              <Input.Password placeholder='请输入密码' />
            </Form.Item>
            <Form.Item
              name='checkCode'
              rules={[
                {
                  required: true,
                  message: '请输入验证码!',
                },
              ]}
            >
              <Row>
                <Col span={8}>
                  <img
                    src={'data:image/jpeg;base64,' + this.state.captchaImage}
                    alt='验证码'
                    height='30px'
                    onClick={this.reset}
                  />
                </Col>
                <Col span={16}>
                  <Input placeholder='请输入验证码' />
                </Col>
              </Row>
            </Form.Item>
            <Form.Item name='remember' valuePropName='checked'>
              <Checkbox
                checked={this.state.rememberPassword}
                onChange={e => {
                  this.setState({ rememberPassword: e.target.checked })
                }}
              >
                记住密码
              </Checkbox>
              <span className='register' onClick={this.toRegister}>
                注册
              </span>
            </Form.Item>

            <Form.Item name='btn'>
              <Button
                type='primary'
                htmlType='submit'
                style={{ width: '100%' }}
                className='login-btn'
                onClick={this.submit}
                loading={this.state.logining}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    )
  }
}
export default withRouter(Index)
